//基本接口地址
const baseUrl = "http://81.68.133.139:3000/api/";
// const baseUrl = "http://localhost:3000/api/";

import NProgress from "nprogress";
//请求数据转换函数
const changUrl = {
  get(data) {
    return (
      "?" +
      JSON.stringify(data).replace(/[{}":,]/g, (val) => {
        switch (val) {
          case '"':
          case "{":
          case "}":
            return "";
          case ",":
            return "&";
          case ":":
            return "=";
        }
      })
    );
  },
  post(data) {
    return JSON.stringify(data).replace(/[{}":,]/g, (val) => {
      switch (val) {
        case '"':
        case "{":
        case "}":
          return "";
        case ",":
          return "&&";
        case ":":
          return "=";
      }
    });
  },
};
const http = {
  get(url, data) {
    NProgress.start();
    if (data) {
      url += changUrl.get(data);
    }
    return fetch(baseUrl + url).then((response) => {
      NProgress.done();
      return response.json();
    });
  },
  post(url, data) {
    NProgress.start();
    return fetch(baseUrl + url, {
      body: JSON.stringify(data),
      method: "POST",
      headers: new Headers({
        "Content-Type": "application/json",
      }),
    }).then((response) => {
      NProgress.done();
      return response.json();
    });
  },
};

export default http;
